<template>
  <div class="page white-stage">
    <div class="team-main">
      <group title="基本设置">
        <!--<x-input title="团队名称" -->
        <!--v-model="team.team_name" -->
        <!--placeholder="请输入团队名称" -->
        <!--novalidate :icon-type="iconType" -->
        <!--:show-clear="false" -->
        <!--@on-blur="onBlur" -->
        <!--placeholder-align="right"></x-input>-->
        <cell @click.native ="selectManager" direction="rtl" title="市场人员" :value="selectManagerValue"  ></cell>
        <!--<cell @click.native="selectMembers" direction="rtl" title="市场人员" :value="selectMembersValue" ></cell>-->
      </group>
      <group title="市场人员" v-if="team_managers && team_managers.length">
        <cell v-for="(member, index) in team_managers" :key="index"  direction="rtl" :title="member.name" >
          <!--<a href="javascript:void(0)" class="upgrade-btn" @click="downgradeMananger(member)" v-if="team_managers.length > 1">降级</a>-->
          <a href="javascript:void(0)" class="upgrade-btn" @click="deleteManager(index)" >删除</a>
        </cell>
      </group>
      <!--<group title="市场人员设置" v-if="team_members && team_members.length">-->
        <!--<cell v-for="(member, index) in team_members" :key="index"  direction="rtl" :title="member.name" >-->
          <!--&lt;!&ndash;<a href="javascript:void(0)" class="upgrade-btn" @click="upgradeMember(member)">升级</a>&ndash;&gt;-->
          <!--<a href="javascript:void(0)" class="upgrade-btn" @click="deleteMember(index)">删除</a>-->
        <!--</cell>-->
      <!--</group>-->
      <div class="btn-group">
        <span class="btn save-btn" @click="handleSaveTeam">保存</span>
      </div>
      </div>
      <confirm v-model="showUpgradeConfirm"
          title="温馨提示"
          @on-confirm="onUpgradeConfirm">
        <p style="text-align:center;">你确定升级成员为主管吗!</p>
      </confirm>
      <confirm v-model="showDowngradeConfirm"
          title="温馨提示"
          @on-confirm="onDowngradeConfirm">
        <p style="text-align:center;">你确定将主管降级为成员吗!</p>
      </confirm>
      <x-dialog v-model="this.$store.state.app.dialogShow" >
        <div class="dialog-message">
          {{ this.$store.state.app.dialogMessage }}
        </div>
        <span class="vux-close" @click="hideDialog">知道了</span>
      </x-dialog>
    <confirm v-model="onDel"
             title="温馨提示"
             @on-confirm="onDelConfirm">
      <p style="text-align:center;">您确定要删除吗？</p>
    </confirm>

      <deliver-consult
      :members="members"
      :isShow="removeDialogShow"
      @on-cancel="onRemoveCancel"
      @on-confirm="onDeleteConfirm"
      height="100%"
      style="background-color:white;" />
    </div>
</template>

<script>
  // import Vue from 'vue'
  // import clientMenu from '../components/client-menu'
  // import {XInput, Group, Selector, Cell, XDialog} from 'vux'
  import XInput from 'vux/src/components/x-input'
  import Group from 'vux/src/components/group'
  import Selector from 'vux/src/components/selector'
  import Confirm from 'vux/src/components/confirm'
  import Cell from 'vux/src/components/cell'
  import XDialog from 'vux/src/components/x-dialog'

  import store from '../store'
  import {showDialog, hideDialog} from '../lib/dialog'
  import { mapActions } from 'vuex'
  import Q from 'q'

  import DeliverConsult from '../components/deliver-consult'

  export default{
    data() {
      return {
        teamId: '',
        team:{},
        iconType: '',
        teamname: '天润校营销团队',
        disables: [],
        team_managers: [],
        team_members: [],
        ding_member_ids: [],
        ding_manager_ids: [],
        onDeleteConfirm () {},
        members: [],
        removeDialogShow: false,
        onDel:false,
        onDelConfirm: function () {},
        initialDingManagersIds: [],
        initialDingMembersIds: [],
        initialSelectedTeamManagers: [],
        initialSelectedTeamMembers: [],
        initialTeamMembers: [],
        initialTeamManagers: [],

        selected_team_managers: [],
        selected_team_members: [],
        selectManagerValue: '选择市场人员',
        selectMembersValue: '请选择营销顾问',

        mkChargerValue: '0',
        counselorValue: '0',
        showUpgradeConfirm: false,
        onUpgradeConfirm: function () {},
        showDowngradeConfirm: false,
        onDowngradeConfirm: function () {},

        // clientSourceValue: '',
        // industryValue: '',
        // teamGenderValue: '',

        marketingChargers: [
        {
          key: '0',
          value: '李丽萍'
        },
        {
          key: '1',
          value: '林宇'
        }
        ],

        counselor: [

        {
          key: '0',
          value:'林丽亲'
        },

        {
          key:'1',
          value:'李美英'}
        ],

        amounts: [

        {
          key: '0',
          value:'100'
        },

        {
          key:'1',
          value:'50'
        }
        ]
      }
    },
    components:{
      XInput,
      Group,
      Selector,
      Cell,
      XDialog,
      Confirm,
      DeliverConsult
    },
    methods: {
      onRemoveCancel () {
        this.onDel = false
        this.removeDialogShow = false
      },
      hideDialog () {
        hideDialog()
      },
      refresh (iscroll) {
        console.log('refresh')
      // Refresh current data
      },

      log () {
        console.log('ee');
      },

      load (iscroll) {
        console.log('load')
        // Load new data
      },

      test () {
        console.log('test')
      },

      onBlur () {
      },

      onShow () {
        console.log(arguments)
      },

      upgradeMember (member) {
        return Q.Promise((resolve, reject) => {
          this.showUpgradeConfirm = true
          this.onUpgradeConfirm = resolve
        })
        .then(() => {
            this.upgradeTeamMember({
              team_id: this.teamId,
              suid: member.suid
            }).then((response) => {
              if (response.data.errcode === 0) {
                this.initTeamInfo(this.teamId)
              } else {
                showDialog(response.data.errmsg);
              }
              this.$nextTick(() => this.$vux.loading.hide())
            })
          }
        )
      },
      downgradeMananger (member) {
        return Q.Promise((resolve, reject) => {
          this.showDowngradeConfirm = true
          this.onDowngradeConfirm = resolve
        })
        .then(() => {
            console.log('member.suid', member.suid)
            this.$vux.loading.show({text: '保存中...'})
            this.downgradeTeamManager({
              team_id: this.teamId,
              suid: member.suid
            }).then((response) => {
              if (response.data.errcode === 0) {
                this.initTeamInfo(this.teamId)
              } else {
                showDialog(response.data.errmsg);
              }
              this.$nextTick(() => this.$vux.loading.hide())
            })
        })
      },
      handleSaveTeam () {
        this.saveTeam()
        this.resetTeamData()
      },

      saveTeam (data) {
        let that = this
        this.$vux.loading.show({text: 'loading'})
        return Q.Promise((resolve, reject) => {
          store.dispatch('saveMarketer', data || that.team)
          .then((response) => {
            if (response.data.errcode === 0) {
              showDialog('保存成功!')
              resolve()
            } else {
              showDialog(response.data.errmsg);
              reject()
              console.debug('系统出错!请联系管理员', response.data)
            }
            this.removeDialogShow = false
            this.$vux.loading.hide()
          }).catch((error) =>{
            reject()
            console.debug(error, '系统出错!请联系管理员')
            this.removeDialogShow = false
            this.$vux.loading.hide()
          })
        })
      },
      delTeamMember (data) {
        console.log(data)
        let that = this
        this.$vux.loading.show({text: 'loading'})
        return Q.Promise((resolve, reject) => {
          store.dispatch('delMarketer', data )
          .then((response) => {
            if (response.data.errcode === 0) {
              showDialog('删除成功!')
              resolve()
            } else {
              showDialog(response.data.errmsg);
              reject()
              console.debug('系统出错!请联系管理员', response.data)
            }
//            this.removeDialogShow = false
            this.onDel = false
            this.$vux.loading.hide()
          }).catch((error) =>{
            reject()
            console.debug(error, '系统出错!请联系管理员')
//            this.removeDialogShow = false
            this.onDel = false
            this.$vux.loading.hide()
          })
        })
      },
      initTeams () {
        this.getTeams({page_size: 300})
        .then((response) => {
          if (response.data.errcode === 0) {
            let teams = typeof response.data.results.teams !== 'undefined' ? response.data.results.teams: []
            teams.forEach((team) => {
              if (team.id !== this.teamId) {
                team.team_managers.forEach((teamItem) => {
                  this.disables.push(teamItem.ding_user_id)
                })
                team.team_members.forEach((teamItem) => {
                  this.disables.push(teamItem.ding_user_id)
                })
              }
            })
          } else {
            console.log('response: ', JSON.stringify(response.data));
          }
        }).catch((error)=>{
          console.debug(error, JSON.stringify(response.data))
        })
      },
      clone (obj) {
        return JSON.parse(JSON.stringify(obj))
      },
      deleteMember (index) {
        return Q.Promise((resolve, reject) => {
          this.removeDialogShow = true
          this.onDeleteConfirm = resolve
        }).then((data) => {
          let team = this.clone(this.team)
          data.suid = this.team.team_members[index].suid
          data.id = team.id
          team.team_members.splice(index, 1)
          console.log('team', team.team_managers)
          this.delTeamMember(Object.assign(data), '删除成功!').then(() => {
            const members = this.team.team_members.splice(index, 1)
            this.selected_team_members.forEach((elem, index) => {
              if (members && members[0].ding_user_id === elem.emplId) {
                this.selected_team_members.splice(index, 1)
              }
            })
          })
        })
      },
      deleteManager (index) {
        return Q.Promise((resolve, reject) => {
//          this.removeDialogShow = true
//          this.onDeleteConfirm = resolve
          this.onDel = true
          this.onDelConfirm = resolve
        }).then(() => {
          let team = this.clone(this.team)
          let data = {}
          data.id = this.team.is_marketer[index].id
          team.is_marketer.splice(index, 1)
          this.delTeamMember(Object.assign(data), '删除成功!').then((a, b, c) => {
            const members = this.team.is_marketer.splice(index, 1)
            this.selected_team_managers.forEach((elem, index) => {
              if (members && members[0].ding_user_id === elem.emplId) {
                this.selected_team_managers.splice(index, 1)
              }
            })
          })
        })
      },
//      deleteManager (index) {
//        console.log(index)
//        return false
//        return Q.Promise((resolve, reject) => {
//          this.removeDialogShow = true
//          this.onDeleteConfirm = resolve
//        }).then((data) => {
//          let team = this.clone(this.team)
//          data.suid = this.team.team_managers[index].suid
//          data.id = team.id
//          team.team_managers.splice(index, 1)
//          this.delTeamMember(Object.assign(data), '删除成功!').then((a, b, c) => {
//            const members = this.team.team_managers.splice(index, 1)
//            this.selected_team_managers.forEach((elem, index) => {
//              if (members && members[0].ding_user_id === elem.emplId) {
//                this.selected_team_managers.splice(index, 1)
//              }
//            })
//          })
//        })
//      },
      // 编辑初始化选择的主管、成员
      initTeamInfo (id) {
        let that = this

//        this.initTeams()

        store.dispatch('getMarketerList')
        .then((response) => {

          if (response.data.errcode === 0) {
            let team_managers = [];
            let selected_team_managers = [];
            let selected_team_members = [];
            let ding_member_ids = []
            let ding_manager_ids = []


            that.team = response.data.results;
            that.team.is_marketer.forEach(function(element){
              // console.log('element.ding_user_id', element, elemnt.suid, element.ding_user_id)
              selected_team_managers.push({
                emplId: element.ding_user_id || element.id,
                name: element.name
              })
              ding_manager_ids.push(element.ding_user_id)
            });

            that.selected_team_managers = selected_team_managers;
            that.team_managers = that.team.is_marketer

            that.team.no_marketer.forEach(function(element) {
              // console.log('element.ding_user_id', element, elemnt.suid, element.ding_user_id)
              selected_team_members.push({
                emplId: element.ding_user_id || element.id,
                name: element.name
              })
              ding_member_ids.push(element.ding_user_id)
            })

            that.ding_manager_ids = ding_manager_ids
            that.ding_member_ids = ding_member_ids

            that.selected_team_members = selected_team_members;
            that.team_members = that.team.no_marketer

            that.members = that.team.is_marketer.concat(that.team.no_marketer)
//            that.team.id = id;
            this.resetTeamData()
          } else {
            console.debug('系统出错!请联系管理员', response.data)
          }
        }).catch((error) => {
          console.log(error)
        })
      },


      selectManager () {

        console.log('selectManager')
        var that = this
        let users = []

        this.selected_team_managers.forEach(function(element){
          users.push(element.emplId)
        })
        console.log(that.ding_member_ids)
        this.callJsApi('biz.contact.choose',
        {
          users: users,
          isNeedSearch: true
          // disabledUsers: this.disables.concat(that.ding_member_ids)
        }).then(function(data){
          console.log(JSON.stringify(data));

          var team_managers = []
          let ding_manager_ids = []

          data.forEach(function(object, index){
            team_managers.push({
              ding_user_id: object.emplId,
              name: object.name
            })
            ding_manager_ids.push(object.emplId)
          });

          const selectedManagers = that.uniqueByKey(that.initialTeamManagers.concat(that.clone(team_managers)), 'ding_user_id')
          that.ding_manager_ids = that.unique(that.initialDingManagersIds.concat(ding_manager_ids))
          that.team_managers = selectedManagers;
          that.team.is_marketer = selectedManagers;
          that.selected_team_managers = that.uniqueByKey(that.initialSelectedTeamManagers.concat(data), 'emplId');
        });
      },
      unique (array) {
        return array.filter((value, index, self) => { 
          return self.indexOf(value) === index;
        })
      },

      selectMembers () {
        var that = this
        let users = []

        this.selected_team_members.forEach(function(element){
          users.push(element.emplId);
        })

        this.callJsApi('biz.contact.choose', {
          users: users,
          isNeedSearch: true,
          disabledUsers: this.disables.concat(this.ding_manager_ids)
        }).then(function(data){

          var team_members = []
          let ding_member_ids = []

          data.forEach(function(object, index) {
            team_members.push({
              ding_user_id: object.emplId,
              name: object.name
            })
            ding_member_ids.push(object.emplId)
          });
          // const selectedMembers = that.uniqueByKey(that.team_members.concat(team_members))
          // that.ding_member_ids = that.uniqueByKey(that.ding_member_ids.concat(ding_member_ids), 'suid')
          // that.team_members = selectedMembers
          // that.team.team_members = selectedMembers
          // that.selected_team_members = data

          const selectedMembers = that.uniqueByKey(that.initialTeamMembers.concat(that.clone(team_members)), 'ding_user_id')
          that.ding_member_ids = that.unique(that.initialDingMembersIds.concat(that.clone(ding_member_ids)))
          that.team_members = selectedMembers;
          that.team.team_members = selectedMembers;
          that.selected_team_members = that.uniqueByKey(that.initialSelectedTeamMembers.concat(data), 'emplId');
        })
      },
      resetTeamData () {
        this.$nextTick(() => {
          this.initialDingManagersIds = this.clone(this.ding_manager_ids)
          this.initialTeamManagers = this.clone(this.team.is_marketer)
          this.initialSelectedTeamManagers = this.clone(this.selected_team_managers)

          this.initialDingMembersIds = this.clone(this.ding_member_ids)
          this.initialTeamMembers = this.clone(this.team.no_marketer)
          this.initialSelectedTeamMembers = this.clone(this.selected_team_members)
        })
      },
      uniqueByKey (list, id) {
        const freshList = {}
        for (const i in list) {
          const item = list[i]
          freshList[item[id]] = item
        }
        return Object.values(freshList)
      },
      ...mapActions({
        getTeams: 'getTeams',
        upgradeTeamMember: 'upgradeTeamMember',
        downgradeTeamManager: 'downgradeTeamManager'
      })
    },

    watch:{

      mkChargerValue(value){
        this.team.orderway = value;
      },
      counselorValue(value){
        this.team.counselor = value;
      },
      amountValue(value){
        this.team.amount = value;
      },

      team_members(value) {

        var selectManagerValue = '';
        var isNotElippse = false;

        this.selected_team_members.forEach(function(object, index){
          if (index < 3) {
            selectManagerValue += (index === 0 ? '': '、')+object.name;
          } else if (isNotElippse === false) {
            selectManagerValue += '...';
            isNotElippse = true;
          }
        });

        this.selectMembersValue = selectManagerValue;
      },

      team_managers (value) {
        var selectManagerValue = ''
        var isNotElippse = false

        this.selected_team_managers.forEach(function(object, index){
          if (index < 3) {
            selectManagerValue += (index === 0 ? '': '、') + object.name;
          } else if (isNotElippse === false) {
            selectManagerValue += '...'
            isNotElippse = true
          }
        })
        this.selectManagerValue = selectManagerValue
      }

    },

    mounted () {
      this.callJsApi('biz.navigation.setTitle', {title: '市场人员设置'})
//      this.teamId = this.$route.query.id
      this.initTeamInfo()
//      console.log('edit-team', JSON.stringify(this.team), this.team.id)
    }
  }
</script>

<style lang='less'>
  @import "../less/index.less";

  .team-main {
    .upgrade-btn {
      color: #42b5e3;
    }

    .no-margin{
      &>*{
      margin: 0
      }
    }

    .add-new-btn{
      width: 60%;
    }

    .btn-group{
      margin: 0 auto;
      margin-top: 15px;
      overflow: hidden;

      &>*{
      width: 50px;
      text-align: center;
      border-radius: 4px;
      padding: 10px;
      margin: 0 auto;
      border: 1px solid rgb(229, 229, 229);
      background-color: white;
      color:#23B2E2;
      display: block;
      }

      .pull-left{
      float: left;
      }

      .pull-right{
      float: right;
      }
    }

  }
</style>
